package com.yksj.healthtalk.ui.doctorstation.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.squareup.timessquare.CalendarFragment;
import com.squareup.timessquare.MonthCellDescriptor;
import com.squareup.timessquare.MonthView.Listener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;

public class DoctorQuerySubscribeServiceActivity extends BaseFragmentActivity implements OnClickListener ,OnItemClickListener,Listener {
	
	CalendarFragment mFragmentView;
	ListView mListView;
	DataListAdapter mAdapter;
	SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyyMMdd");
	Map<String,JSONArray> map = new LinkedHashMap<String,JSONArray>();
	//日期忙,闲
	Map<String,String> map2 = new LinkedHashMap<String, String>();

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_query_subscribe_service_layout);
		
		initUI();
		
		onQueryData();
	}
	
	private void initUI(){
		initTitle();
		setTitle("查看预约服务");
		setBackBtn("返回",this);
		
		mFragmentView = (CalendarFragment)getSupportFragmentManager().findFragmentByTag("calender");
		mListView = (ListView)findViewById(android.R.id.list);
		mAdapter = new DataListAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
	}
	
	
	private void onQueryData(){
		RequestParams params = new RequestParams();
		params.put("Type", "queryRiLiRepeatTime");
		params.put("CUSTOMER_ID",SmartFoxClient.getLoginUserId());
		HttpRestClient.doHttpServiceSetServlet330(params,new JsonsfHttpResponseHandler(this){
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
			}
			@Override
			public void onSuccess(int statusCode, JSONArray response) {
				//点击列表发生状态
				for (int i = 0; i < response.size(); i++) {
					JSONObject jsonObject = response.getJSONObject(i);
					String date = jsonObject.getString("SERVICE_TIME_END");//1990121000
					date = date.substring(0,8);
					String state = jsonObject.getString("ISBUZY");
					
					if(map2.containsKey(date) && "0".equals(state)){//已经包含，且是闲
						map2.put(date, state);
					}else if(!map2.containsKey(date)){
						map2.put(date, state);
					}
					//记录状态
					if(!map2.containsKey(date)){
						//日期闲,忙
						map2.put(date, state);
					}
					
					//选择日期对应的列表
					if(map.containsKey(date)){
						JSONArray array = map.get(date);
						array.add(jsonObject);
					}else{
						JSONArray array = new JSONArray();
						array.add(jsonObject);
						map.put(date, array);
					}
				}
				
				List<Date> busyDates = new ArrayList<Date>();
				List<Date> idleDates = new ArrayList<Date>();
				Set<String> set = map2.keySet();
				for (String key : set) {
					Date date;
					try {
						date = mDateFormat.parse(key);
						if("1".equals(map2.get(key))){
							busyDates.add(date);
						}else{
							idleDates.add(date);
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				mFragmentView.initCalender(null, busyDates, idleDates,DoctorQuerySubscribeServiceActivity.this);
			}
		});
	}
	
	@Override
	public void handleClick(MonthCellDescriptor descriptor) {
		String dateStr = mDateFormat.format(descriptor.getDate());
		mAdapter.onDataChange(map.get(dateStr));
	}
	
	@Override
	public void onChangeMonth(int i) {
		
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		JSONObject jsonObject = mAdapter.getItem(position);
		//详细界面
		Intent intent = new Intent(this,DoctorQuerySubscribeServiceDetailedActivity.class);
		intent.putExtra("json",jsonObject.toJSONString());
		startActivityForResult(intent,100);
	}
	
	
	private class DataListAdapter extends BaseAdapter{
		JSONArray mArray = new JSONArray();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat format1 = new SimpleDateFormat("HH:mm");
		
		public void onDataChange(JSONArray array){
			if(array == null)array = new JSONArray();
			this.mArray = array;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mArray.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mArray.getJSONObject(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final JSONObject jsonObject = getItem(position);
			TextView mTextView = null;
			TextView mTextView2 = null;
			if(convertView == null){
				int type = getItemViewType(position);
				convertView = getLayoutInflater().inflate(R.layout.commn_txt_item,null);
				mTextView = (TextView)convertView.findViewById(R.id.item_title);
				mTextView2 = (TextView)convertView.findViewById(R.id.item_menber);
				convertView.setTag(R.id.item_menber,mTextView2);
				convertView.setTag(R.id.item_title,mTextView);
				if(type == 1){
					convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_background_up));
				}else if(type == 2){
					convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_background_down));
				}else if(type == 3){
					convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.text_background_single));
				}else{
					convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_background_middle));
						
				}
			}else{
				mTextView = (TextView)convertView.getTag(R.id.item_title);
				mTextView2 = (TextView)convertView.getTag(R.id.item_menber);
			}
			if(!jsonObject.containsKey("sevice_name_str")){
				String type = jsonObject.getString("SERVICE_TYPE_ID");
				if("1".equals(type)){
					type = "VIP咨询";
				}else if("2".equals(type)){
					type = "网上咨询";
				}else{
					type = "门诊预约咨询";
				}
				jsonObject.put("sevice_name_str",type);
			}
			mTextView2.setText(jsonObject.getString("sevice_name_str"));
			if(!jsonObject.containsKey("title_time")){
				try {
					String date1 = format1.format(format.parse(jsonObject.getString("SERVICE_TIME_BEGIN")));//12:00
					String date2 = format1.format(format.parse(jsonObject.getString("SERVICE_TIME_END")));
					jsonObject.put("title_time", date1+"-"+date2);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			mTextView.setText(jsonObject.getString("title_time"));
			return convertView;
		}

		@Override
		public int getItemViewType(int position) {
			final int count = getCount();
			if(count == 1) return 3;
			if(position == 0){
				return 1;
			}else if((count -1) == position){
				return 2;
			}else{
				return 0;
			}
		}

		@Override
		public int getViewTypeCount() {
			return 4;
		}
	}
	
}
